# -*- coding: utf-8 -*-

import requests
import time
import hashlib

import json


def token_get(appkey, appsecret):
    # generate timestamp
    timestamp = int(time.time())

    # generate token
    m = hashlib.md5()
    token = appkey + "+" + str(timestamp) + "+" + appsecret
    m.update(token.encode('utf-8'))
    token = m.hexdigest()

    return (token, timestamp)


class API(object):
    def __init__(self, base_url, app_key=None, app_secret=None):
        self.base_url = base_url
        self.app_key = app_key
        self.app_secret = app_secret

    def json_call(self, url, params=None, data=None):
        if not params:
            params = {}
        if not data:
            data = {}

        base_url = self.base_url
        # timeout = self.timeout

        full_url = base_url + url

        headers = {"content-type": "application/json",
                   #    "credentials": "include"
                   }

        # print('json call:', full_url, params, data)

        rspd = requests.post(full_url, params=params,
                             data=json.dumps(data),
                             headers=headers)

        # print(rspd)

        # res = json.loads(rspd.text)
        # print('json_call, res:', res,  type(res))

        res = rspd.json()

        print('json_call, res1:', res,  type(res))

        return res

    def _call(self, url, content):
        token, timestamp = token_get(self.app_key, self.app_secret)

        data = {
            'app_key': self.app_key,
            'token': token,
            'timestamp': timestamp
        }

        data.update(content)

        # print('data:', data)

        params = {}

        res = self.json_call(url, params, data)

        # res = {
        #     'id': '3ee03cba364542319f95cd7541a8c6c1',
        #     'result': 0,
        #     'error': 10025,
        #     'message': 'Invalid appKey'
        # }

        # result = res['result']

        # if result == 0:
        #     error_code = str(res['error'])
        #     error_message = res['message']

        #     print('error_code', error_code)
        #     print('error_message', error_message)

        #     raise Exception({
        #         'code': error_code,
        #         'message': error_message
        #     })

        return res

    def get_item_info(self, content):
        url = '/v1/item/get_item_info'
        # print(content)

        res = self._call(url, content)
        # res = api__json_call__res

        # print('get_item_info ok:', res)

        # res = {
        #     'id': '88d3b6f08d9f404a872f7f0dda6e9b28',
        #     'result': 1, # 1: 成功, 0: 失败
        #     'message': 'success',
        #     'response': {
        #         'data' : {}
        #     }
        # }

        return_result = res['result']
        if return_result != 1:
            raise Exception({
                'code': return_result,
                'message': res['message']
            })

        return_data = res['response']['data']

        # return_data = {
        #     'result': 1,
        #     'id': 'b589ee590a7fb48445fd9404cacabd57',
        #     'message': 'success',
        #     'sha1': 'c8f3df6e7d9a8ff0fd881f2c23f0001d31d0a438',
        #     'time_cost': '766',
        #     'timestamp': 1673426323,
        #     'version': '20201023',
        #     'identify_results': []
        # }

        # data_reuslt = return_data['reuslt']
        # if data_reuslt != 1:
        #     raise Exception({
        #         'code': return_reuslt,
        #         'message': return_data['message']
        #     })

        identify_results = return_data['identify_results']

        # identify_results = [{
        #     'details': {
        #
        #     },
        #     'extra': {
        #         'check_code_candidates': [],
        #         'check_code_last_six': [],
        #         'number_order_error': [],
        #         'qrcode': ['01,10,011002100111,15159313,76.06,20211105,56183922060040110881,BE26,']
        #     },

        #     'orientation': 0,
        #     'image_size': [1712, 1110],
        #     'page': 0,
        #     'type': '10102'
        # }]

        if len(identify_results) != 1:
            raise Exception({
                'code': 'error',
                'message': 'identify_results len error'
            })

        ocr_fapiao = identify_results[0]

        def get_fapiao_details(fp):

            fields = [
                'machine_code', 'code', 'number',
                'check_code',
                'seller', 'seller_tax_id',
                'buyer', 'buyer_tax_id',
                'remark',
                'issuer', 'reviewer', 'receiptor',
                'date',
                'pretax_amount', 'tax', 'total', 'total_cn',

                'company_seal',
                'kind', 'service_name',
                'province', 'city',

            ]
            return dict((k, v) for k, v in fp.items() if k in fields)

        def format_ocr_fapiao(rec):
            one = {}
            one['invoice_type'] = rec['type']
            one['qrcode'] = rec['extra']['qrcode']
            details = rec['details']
            one.update(get_fapiao_details(details))
            return one

        invoice_type = ocr_fapiao['type']

        if invoice_type not in ['10100', '10101', '10102']:
            raise Exception({
                'code': 'error',
                'message': "Not invoice type of ('10100', '10101', '10102')"
            })

        fp = format_ocr_fapiao(ocr_fapiao)

        # print('ocr fp,', fp)

        return fp


# api__json_call__res = {
#     'id': '88d3b6f08d9f404a872f7f0dda6e9b28',
#     'result': 1,
#     'message': 'success',
#     'response': {
#         'data': {
#             'result': 1,
#             'id': 'b589ee590a7fb48445fd9404cacabd57',
#             'message': 'success',
#             'sha1': 'c8f3df6e7d9a8ff0fd881f2c23f0001d31d0a438',
#             'time_cost': '766',
#             'timestamp': 1673426323,
#             'version': '20201023',

#             'identify_results': [
#                 {
#                     'details': {

#                         'code': '011002100111',
#                         'number': '15159313',
#                         'date': '2021年11月05日',
#                         'pretax_amount': '76.06',
#                         'tax': '9.49',
#                         'check_code': '56183922060040110881',
#                         'total': '85.55',
#                         'seller': '北京京东达锐贸易有限公司',
#                         'seller_tax_id': '91110112MA01831F9A',
#                         'buyer': '河南晟华工程管理有限公司张家口分公司',
#                         'buyer_tax_id': '91130703MA0DNJRM8K',
#                         'company_seal': '1',
#                         'form_type': '',

#                         'kind': '办公',

#                         'ciphertext': '-20/648*67--/>8461091862+50,8-*<688++0509/9632+>/17<+62,7+12+6+3457181+6/712630//07,299819<<+1<+831/<6/3+22/402',
#                         'machine_code': '661619946800',
#                         'receiptor': '王陆',
#                         'reviewer': '李思',
#                         'issuer': '王梅',
#                         'province': '北京市',
#                         'city': '',

#                         'service_name': '文具',

#                         'remark': '订单号:229485836626',
#                         'item_names': '*文具*天章(TANGO)施工监理日志日记记录本日记工地施工日志通用单位工程项目记录记事本施工安,志日记记录本日记工地施工日志通用单位工程项目记录记事本施工安, *物流辅助服务*配送费',

#                         'code_confirm': '011002100111',
#                         'electronic_mark': '1',
#                         'total_cn': '捌拾伍圆伍角伍分',
#                         'vehicle_mark': '0',
#                         'company_seal_mark': '1'
#                     },

#                     'extra': {
#                         'check_code_candidates': [],
#                         'check_code_last_six': [],
#                         'number_order_error': [],
#                         'qrcode': ['01,10,011002100111,15159313,76.06,20211105,56183922060040110881,BE26,']
#                     },

#                     'orientation': 0,
#                     'image_size': [1712, 1110],
#                     'page': 0,
#                     'type': '10102'
#                 }
#             ]
#         }
#     }

# }


# fp_type = {
#     '10100': '增值税专用发票',
#     '10200': '定额发票',
#     '10507': '过路费发票',
#     '10101': '增值税普通发票',
#     '10400': '机打发票',
#     '10900': '可报销其他发票',
#     '10102': '增值税电子普通发票',
#     '10500': '出租车发票',
#     '10103': '增值税普通发票(卷票)',
#     '10503': '火车票',
#     '20100': '国际小票',
#     '10104': '机动车销售统一发票',
#     '10505': '客运汽车',
#     '20105': '滴滴出行行程单',
#     '10105': '二手车销售统一发票',
#     '10506': '航空运输电子客票行程单',
#     '10902': '完税证明',
#     '10505a': '船票'
# }
